import React, { useRef } from "react";
import { useNavigate } from "react-router-dom";

import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input, Avatar } from "antd";
import dataManager from "@/utils/dataManager";

import {ACCESS_TOKEN, UID, AVATAR, BACKGROUND, USERNAME} from "../../contains/seesionKeys"

const Login = ({ state, dispatch }) => {
  const { backGroundUrl } = state;

  const navigate = useNavigate();

  const passwordRef = useRef();
  const formRef = useRef();

  const openSignup = () => {
    dispatch({
      type: "setState",
      payload: {
        isLogin: false,
        isRegister: true,
      },
    });
  };

  const onLoginFormFinish = async (value) => {
    try {
      const user = await dataManager.login(value.username, value.password);

      if (backGroundUrl !== user.background)
        dispatch({
          type: "setState",
          payload: {
            backGroundUrl: user.background,
          },
        });

      // 使用localStorage替代sessionStorage，更持久化
      localStorage.setItem(UID, user.uid);
      localStorage.setItem(AVATAR, user.avatar || '');
      localStorage.setItem(BACKGROUND, user.background || '');
      localStorage.setItem(USERNAME, user.username);

      // 设置当前用户
      await dataManager.setCurrentUser(user.uid);

      // 设置状态管理中的用户信息
      dispatch({
        type: "setState",
        payload: {
          isLogin: true,
          backGroundUrl: user.background || '',
          isNotlockScreen: true,
        },
      });

      console.log('Login successful, navigating to desktop...');
      navigate("/desktop");
    } catch (err) {
      formRef.current.setFieldsValue({
        password: "",
      });
      passwordRef.current.focus();
    }
  };

  return (
    <Form
      name="normal_login"
      className="login-form"
      onFinish={onLoginFormFinish}
      ref={formRef}
    >
      <Form.Item style={{ textAlign: 'center' }}>
        <Avatar
          size={100}
          icon={<UserOutlined style={{ color: "rgb(204, 204, 204)" }} />}
          style={{ backgroundColor: "white", opacity: 0.7 }}
        />
      </Form.Item>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "Please input your Username!" }]}
      >
        <Input
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="Username"
          style={{ backgroundColor: "white", opacity: 0.9 }}
        />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "Please input your Password!" }]}
      >
        <Input.Password
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="Password"
          style={{ backgroundColor: "white", opacity: 0.9 }}
          ref={passwordRef}
        />
      </Form.Item>

      <Form.Item>
        <Button
          type="primary"
          style={{
            backgroundColor: "rgb(47, 126, 192)",
            marginRight: "68px",
          }}
          htmlType="submit"
        >
          Sign in
        </Button>
        <span style={{ fontSize: "18px", verticalAlign: "center" }}>
          Or{"   "}
          <a
            style={{ color: "rgb(47, 126, 192)", fontWeight: "600" }}
            onClick={openSignup}
          >
            register now!
          </a>
        </span>
      </Form.Item>
    </Form>
  );
};

export default Login;
